<template>
  <div class="app-container">
    <div v-for="(item, index) in processingRecordList" :key="index" class="Bigbox">
      <div>{{ item.processCode == 0 ? "生产记录" : "第" + item.processCode + "次返工" }}</div>
      <el-steps :active="item.rowslist.length" align-center>
        <el-step v-for="c in getReversedRowslist(item.rowslist)" :key="c.id"
          :description="c.deviceName.substring(0, 6)">
          <template #title>
            <span :style="{ color: c.processingResult == 1 ? '' : 'red' }">
              {{ (c.workstation || '') + '(' + (c.processingResult == 1 ? 'OK' : 'NG') + ')' }}
            </span>
          </template>
        </el-step>
      </el-steps>
    </div>

    <!-- 添加或修改加工过程对话框 -->
    
  </div>
</template>

<script>
import {
  listProcessingRecord,
  getProcessingRecord,
  delProcessingRecord,
  addProcessingRecord,
  updateProcessingRecord
} from "@/api/mes/processing_record";

import { buildColumn } from "@/utils/tableData.js"

export default {
  name: "ProcessingRecord",
  dicts: ['processing_type'],


  data() {
    return {
      props: {
        item: {
          type: Object,
          required: true
        }
      },
      currentStep: 20, // 当前步骤索引，从 0 开始
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      steps: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 加工过程表格数据
      processingRecordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      paramsLables: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 50,
        productSn: null,
        processCode: null,
        deviceId: null,
        processingTime: null,
        processingType: null,
        processParameter: null,
        processingResult: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      columnHeaders: {
        productSn: '产品条码',
        deviceName: '设备名称',
        workstation: '设备工站',
        processingTime: '加工时间',
        processingResult: '加工结果',
        remark: '备注'
      }
    };
  },
  created() {
    const productSn = this.$route.params.sn
    this.queryParams.productSn = productSn
    this.getList();
  },
  mounted() {

  },
  methods: {
    getReversedRowslist(rowslist) {
      return rowslist.slice().reverse(); // 返回倒序数组副本
    },
    containsChinese(str) {
      const regex = /[\u4e00-\u9fa5]+/;
      return regex.test(str);
    },
    downloadExcel() {

      const data = this.processingRecordList.map(row => {
        return Object.keys(row).reduce((obj, key) => {
          let label = this.columnHeaders[key]
          if (label) {
            if (key === 'processingResult') {
              obj[label] = row[key] == 1 ? '合格' : '不合格'
            } else {
              obj[label] = row[key]
            }


          } else {
            if (this.containsChinese(key)) {
              obj[key] = row[key]
            }
          }
          return obj;
        }, {});

      });
      const ws = XLSX.utils.json_to_sheet(data);
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
      XLSX.writeFile(wb, '加工过程.xlsx');
    },
    /** 查询加工过程列表 */
    getList() {
      this.loading = true;
      listProcessingRecord(this.queryParams).then(response => {
        let rowslist = response.rows;
        this.steps = rowslist
        const grouped = rowslist.reduce((acc, row) => {
          const { processCode, ...rest } = row; // 提取 processCode 和其他字段
          if (!acc[processCode]) {
            acc[processCode] = { processCode, rowslist: [] }; // 初始化分组对象
          }
          acc[processCode].rowslist.push(rest); // 将其他字段加入分组
          return acc;
        }, {});

        // 转换为数组
        const result = Object.values(grouped);
        this.processingRecordList = result
        console.log(this.processingRecordList, '11111111');
        // this.reBuildRows(response.rows)
        this.total = response.total;
        this.loading = false;
      });
    },
    reBuildRows(rows) {
      let { dataList, labels } = buildColumn(rows)
      this.paramsLables = labels
      this.processingRecordList = dataList
      console.log(this.paramsLables, '0000');
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        productSn: null,
        processCode: null,
        deviceId: null,
        processingTime: null,
        processingType: null,
        processParameter: null,
        processingResult: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        workstation: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加加工过程";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getProcessingRecord(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改加工过程";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateProcessingRecord(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProcessingRecord(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除加工过程编号为"' + ids + '"的数据项？').then(function () {
        return delProcessingRecord(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('mes/processing/record/export', {
        ...this.queryParams
      }, `processingRecord_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>
.Bigbox {
  margin: 20px 0;
  background-color: #edeff6;
}

.ng-text {
  color: red;
}
</style>